/* eslint-disable */
import './public-path';
import Vue from 'vue'
import App from './App.vue'
import {initRouter} from './router'
import './theme/index.less'
import '@/plugins/antd'
import '@/plugins/element'
import '@/plugins/vxeTable'
// import '@/mock'
import store from './store'
import 'animate.css/source/animate.css'
import '@/assets/style/common.less'
import Plugins from '@/plugins'
import {initI18n} from '@/utils/i18n'
import bootstrapPri from '@/bootstrap'
import 'moment/locale/zh-cn'
import { setAuthorization } from "@/utils/request"
import md5 from 'js-md5'
import { storeQiankun } from 'if-qiankun-config'
import echarts from "@/plugins/echarts"; // 添加echarts图
import IfCaptcha from '@/components/if-captcha'

Vue.prototype.$md5 = md5
const qianKunInstance = storeQiankun.Instance
// 挂载到vue实例中
Vue.prototype.$echarts = echarts

let router = null
let instance = null;
const i18n = initI18n('CN', 'US')
Vue.config.productionTip = false
Vue.use(Plugins)
Vue.use(IfCaptcha)

function render(props = {}) {
  const { container } = props;
  router = initRouter(store.state.setting.asyncRoutes)
  bootstrapPri({router, store, i18n, message: Vue.prototype.$message})
  instance = new Vue({
    router,
    store,
    i18n,
    render: h => h(App)
  }).$mount(container ? container.querySelector('#car-app') : '#car-app');
}
// 独立运行时
if (!window.__POWERED_BY_QIANKUN__) {
  render()
}

/**
 * 从Authorization中获取token
 * @param {*} Authorization
 * @returns
 */
const getTokenFromAuthorization = (Authorization) => {
  return Authorization.includes('Bearer') ? Authorization.replace('Bearer ', '') : Authorization
}

// 兼容旧业务的处理
const adaptOldBusiness = (value) => {
  const { enterpriseId, departmentId, roleId, openId, Authorization, token, loginUserInfo } = value
  console.log(value)
  store.commit('account/setLoginUserInfo', loginUserInfo)
  if (value.fromSystem && (value.fromSystem === 'fleet-if' || value.fromSystem === 'fleet-center' || value.fromSystem === 'tass' || value.fromSystem === 'user-center' || value.fromSystem === 'isc-if')) {
    // 车队是父应用 or tass
    window.fromSystem = value.fromSystem
  } else if (value.fromSystem === 'flxt') {
    window.fromSystem = value.fromSystem
  }
  setAuthorization(
    {
      enterpriseId
    },
    "basic"
  );
  setAuthorization({
    departmentId,
    roleId,
  }, 'auth1');
  setAuthorization({
    token: getTokenFromAuthorization(Authorization || token),
    openId
  });
}

/**
 * 兼容父子通信传递过来的数据
 * @param {*} value 主要数据
 * 重要字段一览：
 * appId, openId, enterpriseId, enterpriseList, appProperty
 * departmentId, departmentName, roleId, Authorization(token)
 * userName, smallTenancyStatus, fromSystem, user(loginUserInfo)
 */
const adaptCrossData = (value) => {
  const { 
    Authorization, token,
    user, loginUserInfo
  } = value
  // token字段 (之前是：Authorization) 如果主系统有多个子系统，用了不同字段，还得用最初的 Authorization
  if (!token && Authorization) {
    value.token = getTokenFromAuthorization(Authorization)
    delete value.Authorization
  }
  // loginUserInfo 字段 (之前是：user)
  if (!loginUserInfo && user) {
    value.loginUserInfo = user
    delete value.user
  }
}

export async function bootstrap() {
  // console.log('[vue] vue app bootstraped');
}

export function mount(props) {
  qianKunInstance.actions = props; // 初始化actions对象
  const { DISPENSE_USER_INFO, LOG_OUT, UPDATE_MAIN_APP_TOP_NAME } = storeQiankun.ActionsFromMainSystem
  props.onGlobalStateChange(async (state) => {
    let needRender = true
    qianKunInstance.state = state; // 同步当前状态
    const { action, value } = state
    console.log(value)
    switch (action) {
      case DISPENSE_USER_INFO: {
        adaptCrossData(value) // 兼容数据格式
        adaptOldBusiness(value) // 同步之前业务中的cookie代码
        store.commit('account/setNewState', value) // 本地存储
        break
      }
      // 退出登录
      case LOG_OUT: {
        needRender = false // 关闭
        break
      }
      // 个人信息更新姓名
      case UPDATE_MAIN_APP_TOP_NAME: {
        needRender = false // 关闭
        break
      }
      default:
    }
    needRender && await render(props)
  });
}

export async function unmount() {
  instance.$destroy();
  instance.$el.innerHTML = '';
  instance = null;
  router = null;
}
